import * as amqp from "amqplib";

// RabbitMQ 服务器的连接信息
const rabbitMQServer = "amqp://mingcai_mq:EUDNfpZRbhfjb8PZ@95.169.25.181";

// 定义订单阶段主题
enum OrderStage {
    Created = "order.created",
    Paid = "order.paid",
    Shipped = "order.shipped",
}

// 订单消息数据格式
interface OrderMessage {
    orderId: string;
    stage: OrderStage;
    // 其他订单信息字段...
}

// 消费主订单消息
async function consumeMainOrderMessages() {
    try {
        // 创建 RabbitMQ 连接
        const connection = await amqp.connect(rabbitMQServer);
        const channel: amqp.Channel = await connection.createChannel();

        // 定义交换机名称
        const exchangeName = "order_exchange";

        // 声明主题交换机
        await channel.assertExchange(exchangeName, "topic", {durable: false});

        // 声明队列
        const queue = await channel.assertQueue("main_order_queue", {exclusive: true});

        // 绑定队列到交换机，关注订单的 created 和 paid 阶段
        await channel.bindQueue(queue.queue, exchangeName, "order.created");
        await channel.bindQueue(queue.queue, exchangeName, "order.paid");

        // 接收主订单消息
        console.log("[*] Waiting for main order messages. To exit press CTRL+C");
        await channel.consume(
            queue.queue,
            (msg) => {
                if (msg && msg.content) {
                    const orderMessage: OrderMessage = JSON.parse(msg.content.toString());
                    console.log(`[x] Received main order message - Order ID: ${orderMessage.orderId}, Stage: ${orderMessage.stage}`);
                }
            },
            {noAck: true} // 不需要手动确认消息
        );
        // 关闭连接
        process.on('SIGINT', () => {
            console.log('consume exit, close connection...');
            channel.close()
            connection.close();
        });
    } catch (error) {
        console.error("Error in consumeMainOrderMessages:", error);
    }
}

// 启动消费者
consumeMainOrderMessages();
